package com.ordertracker.security;

import com.ordertracker.Application;
import com.ordertracker.Session;
import com.sun.jersey.oauth.server.OAuthServerRequest;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
import com.sun.jersey.oauth.signature.OAuthSignature;
import com.sun.jersey.oauth.signature.OAuthSignatureException;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import javax.ws.rs.ext.Provider;
import javax.xml.ws.WebServiceException;
import java.util.Date;
import java.util.Map;

/**
 * Description of class.
 * Created 1/9/13 3:56 PM
 *
 * @author andrey.rodin@playtech.com
 */
@Component
@Provider
public class SecurityContextFilter implements ResourceFilter, ContainerRequestFilter {

    private Map<String, Session> sessionMap = Application.getApplication().getSessionCash();

    @Override
    public ContainerRequest filter(ContainerRequest request) {
        if ("accounts/login".equals(request.getPath())) {
            return request;
        }

        OAuthServerRequest serverRequest = new OAuthServerRequest(request);
        OAuthParameters parameters = new OAuthParameters();
        parameters.readRequest(serverRequest);
        String token = parameters.get("oauth_token");
        if (null == token) {
            throw new WebServiceException("Not Authorization !");
        }
        Session session = sessionMap.get(token);

        if (session == null) {
            throw new WebServiceException("Not Authorization !");
        }

        OAuthSecrets secrets = new OAuthSecrets();
        secrets.consumerSecret("Q1jk4]%@fddo$fds=FDS");
        parameters.setConsumerKey(session.getSessionKey());

        try {
            if (! OAuthSignature.verify(serverRequest, parameters, secrets)) {
                throw new OAuthSignatureException("Not Authorization !");
            }
        } catch (OAuthSignatureException e) {
            throw new WebServiceException("Not Authorization !", e);
        }

        session.setLastAccessedDate(new Date(System.currentTimeMillis()));
        request.setSecurityContext(new ApplicationSecurityContext(session));

        return request;
    }

    @Override
    public ContainerRequestFilter getRequestFilter() {
        return this;
    }

    @Override
    public ContainerResponseFilter getResponseFilter() {
        return null;
    }
}
